// pages/push/push.js
const DB = wx.cloud.database().collection("commentlist")
let name = ""
let url = ""
let infoimage=''
let infonickname=''
let pinlun=''
var app=getApp()

Page({
  data:{
    ischoose:false,
    showbutton:true,
    tempFilePaths:'',
  },
  // 获取输入框中的类型
  addName(event) {
    console.log(event.detail.value)
    name = event.detail.value
  },
  // 留言板数据绑定
addDetail(event){
  console.log(event.detail)
  this.setData({detail:event.detail})
  pinlun:this.data.detail
},
  // 获取图片上传后的url路径
  addImagePath(fileId) {
    console.log(fileId)
    wx.cloud.getTempFileURL({
      fileList: [fileId],
      success: res => {
        url = res.fileList[0].tempFileURL
        this.setData({showbutton:false})
      },
      fail: console.error
    })
  },
  //上传文件到云储存
  upload(){
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        console.log("成功",res);
        // const tempFilePaths = res.tempFilePaths
        // console.log('零食地址',tempFilePaths)
        that.uploadImage(res.tempFilePaths[0])
        that.setData({
          tempFilePaths:res.tempFilePaths[0],
          ischoose:true
        })
      }
    })
  },
  //提交数据到数据库中
  addData() {
    this.setData({ischoose:false})
    this.setData({showbutton:true})
    if (name.length==0) {
      wx.showToast({
        title: '题目类型不能为空！',
        icon:'error'
      })
    return
    }
    if (this.data.tempFilePaths.length==0) {
      wx.showToast({
        title: '请选择图片！',
        icon:'error'
      })
     return
    }
    else{
      infoimage:app.globalData.info.avatarUrl
      infonickname:app.globalData.info.nickName
    DB.add({
      data: {
        name: name,
        url: url,
        detail:this.data.detail,
        dianzannum:0,
        comment:[{
          infoimage:infoimage,
          infonickname:infonickname,
          pinlun:pinlun
        }]
      },
      success(res) {
        console.log("添加成功", res)
        wx.showToast({
          title: '上传成功',
          icon:"success"
        })
      },
      fail() {
        console.log("添加失败", res)
      }
    })
  }
},

  // 上传到云开发的存储中
  uploadImage(fileURL) {
    var that = this
    wx.cloud.uploadFile({
      cloudPath:new Date().getTime()+'.png', // 上传至云端的路径
      filePath: fileURL, // 小程序临时文件路径
      success: res => {
        //获取图片的http路径
        that.addImagePath(res.fileID)
      },
      fail: console.error
    })
  },
  onShow(){
   
  },
  onload(){
    this.setData({
      info:app.globalData.info
    })
  }
})
